import Core.IO as IO
import Core.MongoDB as MongoDB
import Core.Gadget as Gadget
import datetime
from WindPy import *
w.start()


def StockList(database):
    trades = database.find("Instruments", "Stock")
    symbols = []
    ipo_dates = []
    for trade in trades:
        symbol = trade["Symbol"]
        ipo_date = trade["DateTime1"]
        symbols.append(symbol)
        ipo_dates.append(ipo_date)
    return [symbols, ipo_dates]

database = MongoDB.MongoDB("10.13.38.5", "27017")
#stocks = StockList(database)

database.creatIndex("Factor", "Dividend", "Key")
database.creatIndex("Factor", "Dividend", "StdDateTime")
database.creatIndex("Factor", "Dividend", "Symbol")

instruments = database.find("Instruments", "Stock")

# symbols = stocks[0]
# ipo_dates = stocks[1]

# for i in range(len(symbols)):
count = 0
for instrument in instruments:
    symbol = instrument["Symbol"]
    ipo_date = instrument["DateTime1"]
    delist_date = instrument["DateTime2"]
    count += 1
    print(symbol, count)

    # ipo_date = Gadget.ToUTCDateTime(ipo_date)
    datetime1 = Gadget.ToUTCDateTime(datetime(2000, 1, 1, 0, 0, )) + timedelta(days=-1)
    datetime2 = Gadget.ToUTCDateTime(datetime.utcnow())
    #
    if ipo_date > datetime1:
        datetime1 = ipo_date
    if delist_date < datetime2:
        datetime2 = delist_date

    # ---返回的都是当天24点值，也就是第二天0点数值---
    month_list = IO.GenerateEndDayofMonth(datetime1, datetime2)

    lastDate = None
    for j in range(len(month_list)):
        std_end_datetime = month_list[j]
        #
        print(symbol,"#month",j,std_end_datetime)

        end_date_midnight = Gadget.ToLocalDateTime(std_end_datetime) # 返回的都是标准时间
        end_date = (end_date_midnight + timedelta(days=-1)).date() # datetime 第二天0点变成前一天0点，再只取日期
        #
        start_date = lastDate
        #
        lastDate = end_date
        if j == 0:
            continue

        str_thisYear_date = Gadget.ToDateString(date(end_date.year,1,1))
        str_start_date = Gadget.ToDateString(start_date + timedelta(days=1))
        str_end_date = Gadget.ToDateString(end_date)

        #
        a = w.wss(symbol, "div_cashpaidbeforetax,div_cashpaidaftertax", #div_aualaccmdiv2,
                  "unit=1;startDate=" + str_start_date + ";endDate=" + str_end_date + ";currencyType=;dateType=0")

        #
        b = w.wss(symbol, "div_aualaccmdiv2",
                  "unit=1;startDate=" + str_thisYear_date + ";endDate=" + str_end_date + ";currencyType=;dateType=0")

        #print(j)
        debug = 1

        #
        followersDoc = {}
        followersDoc["Symbol"] = symbol

        if a.Data[0][0] == None:
            followersDoc["CashPaidBeforeTax"] = 0
        else:
            followersDoc["CashPaidBeforeTax"] = a.Data[0][0]
        if a.Data[1][0] == None:
            followersDoc["CashPaidAfterTax"] = 0
        else:
            followersDoc["CashPaidAfterTax"] = a.Data[1][0]

        #
        if b.Data[0][0] == None:
            followersDoc["AccumulatedDividend"] = 0
        else:
            followersDoc["AccumulatedDividend"] = b.Data[0][0]

        #

        followersDoc["StdDateTime"] = std_end_datetime
        followersDoc["StartDate"] = datetime.combine(start_date, datetime.min.time())
        followersDoc["EndDate"] = datetime.combine(end_date, datetime.min.time())

        followersDoc["Key"] = symbol + "_Dividend_Factor_" + Gadget.ToDateTimeString(end_date_midnight)
        debug =1
        # print(followersDoc)
        database.upsert("Factor", "Dividend", {"Key": followersDoc["Key"]}, followersDoc)
        k = 0
    #print(symbol,"Finished")


